package com.example.alibabanacosdiscoveryclient01.controller;

import com.alibaba.cloud.commons.lang.StringUtils;
import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.client.McpSyncClient;
import io.modelcontextprotocol.client.transport.ServerParameters;
import io.modelcontextprotocol.client.transport.StdioClientTransport;
import io.modelcontextprotocol.spec.McpSchema;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.mcp.SyncMcpToolCallback;
import org.springframework.ai.mcp.SyncMcpToolCallbackProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.nio.file.Paths;
import java.time.Duration;
import java.util.List;

/**
 * @author:guoq
 * @date:2025/4/1
 * @descripion:
 */

@RestController
@RequestMapping("/ai")
@Tag(name = "mcp手动应用")
public class MCPController {
    @Resource
    private ChatClient chatClient;

    @Autowired
    ChatClient.Builder builder;
    @GetMapping("/mcp/getFile")
    @Operation(summary = "访问本地文件")
    public String call() {
        //初始化 McpClient
        String path = Paths.get(System.getProperty("user.dir")).toString();
        ServerParameters stdioParams = ServerParameters.builder("D:\\developdependence\\node\\npx.cmd")
                .args("-y", "@modelcontextprotocol/server-filesystem", path)
                .build();
        McpSyncClient mcpClient = McpClient
                .sync(new StdioClientTransport(stdioParams))
                .requestTimeout(Duration.ofSeconds(10))
                .build();

        McpSchema.InitializeResult initialize = mcpClient.initialize();
        System.out.println("McpClient initialized:"+initialize);

        //声明 MCP Function Callbacks 获取MCP服务器中的工具列表
        List<SyncMcpToolCallback> functionCallbacks = mcpClient.listTools(null)
                // 将每个工具转换为Function Callback
                .tools()
                .stream()
                .map(tool -> new SyncMcpToolCallback(mcpClient, tool))
                .toList();
        //声明 ChatClient
        ChatClient chatClient = builder.defaultTools(functionCallbacks.toArray(new SyncMcpToolCallback[0]))
                .build();

        // Question 1
        String question1 = "你能解释一下spring-ai-mcp-overview.txt文件的内容吗？";
        System.out.println("问题1: " + question1);
        System.out.println("助手回答: " + chatClient.prompt(question1).call().content());

        // Question 2
        String question2 = "请将spring-ai-mcp-overview.txt文件的内容进行汇总，要中文，并保存为新的summary.md为Markdown格式";
        System.out.println("\n问题2: " + question2);
        System.out.println("助手回答: " +
                chatClient.prompt(question2).call().content());
        return "success";
    }

    @GetMapping("/mcp/getSqlite")
    @Operation(summary = "访问sqlite")
    public String sqlite() {
        //初始化 McpClient
        String path = Paths.get(System.getProperty("user.dir"),"test.db").toString();
        ServerParameters stdioParams = ServerParameters.builder("uvx")
                .args("mcp-server-sqlite", "--db-path", path)
                .build();
        McpSyncClient mcpClient = McpClient
                .sync(new StdioClientTransport(stdioParams))
                .requestTimeout(Duration.ofSeconds(10))
                .build();

        McpSchema.InitializeResult initialize = mcpClient.initialize();
        System.out.println("McpClient initialized:"+initialize);

        //声明 MCP Function Callbacks 获取MCP服务器中的工具列表
        List<SyncMcpToolCallback> functionCallbacks = mcpClient.listTools(null)
                // 将每个工具转换为Function Callback
                .tools()
                .stream()
                .map(tool -> new SyncMcpToolCallback(mcpClient, tool))
                .toList();
        //声明 ChatClient
        ChatClient chatClient = builder.defaultTools(functionCallbacks.toArray(new SyncMcpToolCallback[0]))
                .build();

        // Question 1
        String question1 = "你能连接到我的SQLite数据库并告诉我有哪些产品可用，以及它们的价格吗？";
        System.out.println("问题1: " + question1);
        System.out.println("助手回答: " + chatClient.prompt(question1).call().content());

        // Question 2
        String question2 = "数据库中所有产品的平均价格是多少？";
        System.out.println("\n问题2: " + question2);
        System.out.println("助手回答: " + chatClient.prompt(question2).call().content());

        // Question 3
        String question3 = "你能分析价格分布并提出价格优化建议吗？";
        System.out.println("\n问题3: " + question3);
        System.out.println("助手回答: " + chatClient.prompt(question3).call().content());

        // Question 4
        String question4 = "你能帮我设计和创建一个新的表来存储客户订单吗？";
        System.out.println("\n问题4: " + question4);
        System.out.println("助手回答: " + chatClient.prompt(question4).call().content());

        return "success";
    }
}

